<template>
  <div class="assignment-header">
    <img src="@/assets/svgs/left.svg" alt="Back" class="back-button" @click="router.push('/teacher/feedback/card')"/>
    <span class="correct_header1">已提交{{ feedback_header }}人</span>
  </div>
  <div v-if="loading">正在加载问卷结果...</div>
  <div v-else-if="error">加载失败，请稍后再试</div>
  <div v-else class="satisfaction-survey">
    <div  class="satisfaction-chart1">
      <div class="serial">
        <div class="serial1">1</div>
        <div class="serial2">学生建议</div>
      </div>
      <el-table :data="totalCount" style="width: 100%;">
        <el-table-column prop="nickName" label="学生昵称" width="300">
          <template #default="scope">
            {{ scope.row.nickName }}
          </template>
        </el-table-column>
        <el-table-column prop="userName" label="学生账号" width="300">
          <template #default="scope">
            {{ scope.row.userName }}
          </template>
        </el-table-column>
        <el-table-column prop="opnion" label="学生建议" width="700">
          <template #default="scope">
            {{ scope.row.opnion }}
          </template>
        </el-table-column> 
      </el-table> 
    </div> 
    <div v-for="(question, index) in questions" :key="index" class="satisfaction-chart">
      <div class="serial">
        <div class="serial1">{{ index + 2 }}</div>
        <div class="serial2">{{ question.name }}</div>
      </div>
      <el-table :data="question.counts.value" style="width: 100%;">
        <el-table-column prop="option" label="选项" width="600">
          <template #default="scope">
            {{ question.options[scope.$index] }}
          </template>
        </el-table-column>
        <el-table-column prop="count" label="计数" width="300">
          <template #default="scope">
            {{ question.counts.value[scope.$index] }}
          </template>
        </el-table-column> 
        <el-table-column label="百分比">
          <template #default="scope">
            <div class="demo-progress">
              <el-progress
                :text-inside="true"
                :stroke-width="24"
                :percentage="calculatePercentage(question.counts.value[scope.$index], question.total)"
                status="success"
                :color="customColor"
              />
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import { surveyService,suggestionService } from '@/api/feedbackresult';
import { useCounterStore } from "@/stores/counter";

// 从 Pinia 获取课程 ID
let store = useCounterStore();
const courseManageId = store.courseManageId;
console.log("获取的课程id:", courseManageId);

// 获取问卷 ID
const route = useRoute();
const surveyId = ref(null);
surveyId.value = route.params.surveyId;
console.log("获取到的问卷Id:", surveyId.value);

const loading = ref(true);
const error = ref(false);
const feedback_header = ref();
const customColor = ref('#13227A');

const totalCount = ref({});
const totalPercentage  = async () => {
  try {
    const response = await suggestionService(surveyId.value);
    console.log("API123:", response);
    totalCount.value = response.data; 
  }catch (err) {
    error.value = true;
    ElMessage.error(`获取问卷内容失败，请稍后再试: ${err.message}`);
    console.error('Error:', err);
    loading.value = false;
  } 
}
totalPercentage();

const questions = ref([
  {
    name: '环境满意度',
    options: ['95-100很满意', '90-95满意', '80-90较满意', '60-80一般', '30-60不满意', '0-30很不满意'],
    counts: ref([0, 0, 0, 0, 0, 0]),
    total: ref(0)
  },
  {
    name: '互动满意度',
    options: ['95-100很满意', '90-95满意', '80-90较满意', '60-80一般', '30-60不满意', '0-30很不满意'],
    counts: ref([0, 0, 0, 0, 0, 0]),
    total: ref(0)
  },
  {
    name: '教师满意度',
    options: ['95-100很满意', '90-95满意', '80-90较满意', '60-80一般', '30-60不满意', '0-30很不满意'],
    counts: ref([0, 0, 0, 0, 0, 0]),
    total: ref(0)
  },
  {
    name: '速度满意度',
    options: ['95-100很满意', '90-95满意', '80-90较满意', '60-80一般', '30-60不满意', '0-30很不满意'],
    counts: ref([0, 0, 0, 0, 0, 0]),
    total: ref(0)
  },
  {
    name: '理解满意度',
    options: ['95-100很满意', '90-95满意', '80-90较满意', '60-80一般', '30-60不满意', '0-30很不满意'],
    counts: ref([0, 0, 0, 0, 0, 0]),
    total: ref(0)
  }
]);

const calculatePercentage = (count, total) => {
  return total > 0 ? ((count / total) * 100).toFixed(2) : 0;
};

const resultsur = async () => {
  try {
    const response = await surveyService(surveyId.value);
    console.log("API Response:", response);

    if (!response.data || !response.data) {
      throw new Error("Invalid response data");
    }

    const responseData = response.data;

    questions.value[0].counts.value = responseData.environmentCount;
    questions.value[1].counts.value = responseData.interactionCount;
    questions.value[2].counts.value = responseData.satisfactionCount;
    questions.value[3].counts.value = responseData.speedPercentCount;
    questions.value[4].counts.value = responseData.understandCount;

    questions.value[0].total = responseData.countSum;
    questions.value[1].total = responseData.countSum;
    questions.value[2].total = responseData.countSum;
    questions.value[3].total = responseData.countSum;
    questions.value[4].total = responseData.countSum;
    feedback_header.value = responseData.countSum;
    console.log("反馈:", questions);
    loading.value = false;
  } catch (err) {
    error.value = true;
    ElMessage.error(`获取问卷内容失败，请稍后再试: ${err.message}`);
    console.error('Error:', err);
    loading.value = false;
  }
};

onMounted(() => {
  if (!surveyId.value) {
    ElMessage.error('无效的问卷 ID');
    router.push('/teacher/feedback/card');
    return;
  }
  resultsur();
});

const router = useRouter();
</script>

<style scoped>
.assignment-header {
  display: flex;
  height: 7lvh;
  width: 99lvw;
  background-color: #13227A;
  color: white;
}

.back-button {
  background-color: transparent;
  width: 3%;
  height: 7lvh;
  color: white;
  cursor: pointer;
}

.correct_header1 {
  margin-left: 89%;
  font-size: 20px;
  font-weight: 700;
  margin-top: 1%;
}

.satisfaction-survey {
  padding: 20px;
  background-color: #ffffff;
}

.satisfaction-chart {
  margin-top: 20px;
}

.satisfaction-chart1 {
  margin-top: 5px;
  margin-bottom: 20px;
  max-height: 30lvh;
  overflow-y: auto;
}

.demo-progress .el-progress--line {
  max-width: 600px;
}

.serial {
  display: flex;
  width: 100%;
  height: 20px;
}

.serial1 {
  float: left;
  color: white;
  background-color: #13227A;
  width: 20px;
  height: 20px;
  text-align: center;
  border-radius: 50%;
}

.serial2 {
  margin-left: 5px;
  font-size: 17px;
  font-weight: 700;
}
</style>